import os
from urllib.parse import unquote

import aiofiles
import falcon
import App_setting as setting
from WebBackend.dataclass.Directory import path_is_valid
from WebBackend.middleware.virtualWorldGate_Chuche import login_require
from WebBackend.utils import mylog


@falcon.before(login_require)
class SendFileAPI:
    def __init__(self, config=None, store=None):
        pass

    async def on_get(self, req: falcon.Request, resp: falcon.Response):
        file_path = req.params.get('p')
        file_path = unquote(file_path)
        if not path_is_valid(file_path):
            raise falcon.HTTPNotAcceptable(title='invalid path')
        if not os.path.exists(file_path):
            raise falcon.HTTPNotFound(title="文件不存在")
        mylog.info(f'Sending file: {file_path}', req.remote_addr)
        resp.stream = await aiofiles.open(file_path, 'rb')
        resp.content_type = 'binary/file'

    """async def on_post(self, req, resp):
  
        # OK
        if req.params.get('t') == 'u':
            file_dir = setting.file_upload_dir_path
        elif req.params.get('t') == 'd':
            file_dir = setting.file_download_dir_path
        else:
            raise falcon.HTTPError(falcon.HTTP_403, title="query error", description='上传失败，请求路径错误')

        form = await req.get_media()
        async for part in form:
            if part.name.startswith('file'):
                if setting.upload_use_ASCII_filename:
                    file_path = os.path.join(file_dir, part.secure_filename)
                else:
                    file_path = os.path.join(file_dir, part.filename)
                if os.path.isfile(file_path):
                    raise falcon.HTTPError(falcon.HTTP_400, title="上传失败：存在同名文件")
                else:
                    async with aiofiles.open(file_path, 'wb') as f:
                        await part.stream.pipe(f)
                    mylog.data(f'Receiving {file_path}', req.remote_addr)
                    resp.text = '上传成功'
            else:
                raise falcon.HTTPBadRequest(title="错误的表单字段", description="not start with file")

    async def on_delete(self, req, resp):
        # OK
        # r = await req.bounded_stream.read()
        target = req.params.get('file')
        target = target.lstrip('/fields/download?file=')
        try:
            os.remove(os.path.join(setting.file_download_dir_path, target))
            mylog.warn(f'Deleted {target}', req.remote_addr)
            resp.status = falcon.HTTP_200
            resp.text = 'ok'
        except PermissionError as e:
            raise falcon.HTTP_500(title='拒绝访问，无删除权限')
        except FileNotFoundError as e:
            raise falcon.HTTPNotFound(title="文件不存在")"""
